package com.sbtr.business.jupyterhub.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sbtr.open.jupyterhub.dto.JupyterHubDto;
import com.sbtr.business.jupyterhub.entity.JupyterHub;
import com.sbtr.business.jupyterhub.mapper.JupyterHubMapper;
import com.sbtr.business.jupyterhub.service.JupyterHubService;
import com.sbtr.util.BeanCopyUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.List;

@Transactional
@Service
public class JupyterHubServiceImpl extends ServiceImpl<JupyterHubMapper, JupyterHub> implements JupyterHubService{
	
	@Value("${oss.config.order}")
	private String jupyterShell;
	//="/usr/local/jupyter/jupyter2/test.sh";


	@Override
	public JupyterHubDto findByName(String username){

		//查询是否数据库已经存在
		QueryWrapper<JupyterHub> wrapper = new QueryWrapper<>();
		wrapper.in("user_name", username);
		List<JupyterHub> list = list(wrapper);
		if(list.size()>0){//数据库存在
			JupyterHub jupyterHub=list.get(0);
			JupyterHubDto jupyterHubDto =BeanCopyUtils.copyProperties(jupyterHub, JupyterHubDto.class);
		    return jupyterHubDto;
		}
		else{
			invokeShell(username);//linux添加
			JupyterHub jupyterHub=new JupyterHub();
			jupyterHub.setUserName(username);
			jupyterHub.setUserPasswd(username);
			save(jupyterHub);//数据库保存
			JupyterHubDto jupyterHubDto=new JupyterHubDto();
			jupyterHubDto.setUserName(username);
			jupyterHubDto.setUserPasswd(username);
			return jupyterHubDto;
		}
	}
	
	
	public void  invokeShell(String username){
		//方法1 执行字符串命令（各个参数1234之间需要有空格）
		String path="sh "+jupyterShell+" "+username;
		//方法2 在单独的进程中执行指定命令和变量。 
		//第一个变量是sh命令，第二个变量是需要执行的脚本路径，从第三个变量开始是我们要传到脚本里的参数。
	//	String[] path=new String[]{"sh","/root/zpy/zpy.sh","1","2","3","4"}; 
				try{
					Runtime runtime = Runtime.getRuntime();
					Process pro = runtime.exec(path);
					int status = pro.waitFor();
					if (status != 0)
					{
						System.out.println("Failed to call shell's command");
					}
		 
					BufferedReader br = new BufferedReader(new InputStreamReader(pro.getInputStream()));
					StringBuffer strbr = new StringBuffer();
					String line;
					while ((line = br.readLine())!= null)
					{
						strbr.append(line).append("\n");
					}
		 
					String result = strbr.toString();
					System.out.println(result);
		 
				}
				catch (IOException ec)
				{
					ec.printStackTrace();
				}
				catch (InterruptedException ex){
					ex.printStackTrace();
		 
				}
			}
}
